package com.lambkit.module.cms.web.directive;

import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;

import java.util.List;

/**
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Title: 相关文章
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("relevantArticles")
public class RelevantArticlesDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {
        CmsArticle article = getPara(0, scope);
        if (article == null) {
            throw new IllegalArgumentException("#relevantArticles(...) argument must not be null or empty." + getLocation());
        }

        //默认值 3
        int count = getParaToInt(1, scope, 3);

        List<CmsArticle> relevantArticles = CmsArticle.service().findRelevantListByArticleId(article.getArticleId(), CmsArticle.STATUS_NORMAL, count);

        if (relevantArticles == null || relevantArticles.isEmpty()) {
            return;
        }

        scope.setLocal("relevantArticles", relevantArticles);
        renderBody(env, scope, writer);
    }

    @Override
    public boolean hasEnd() {
        return true;
    }
}
